package com.arelikebrothers.demo.concurrent.algo.pc;

import java.util.Random;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by lennon on 04/05/2017.
 */
public class Producer implements Runnable {
    private volatile boolean isRunning = true;
    private BlockingQueue<PCData> queue;
    private static AtomicLong count = new AtomicLong(0L);
    private static final int SLEEPTIME = 100;

    public Producer(BlockingQueue<PCData> queue) {
        this.queue = queue;
    }


    @Override
    public void run() {
        PCData data = null;
        Random random = new Random();

        System.out.println("Start producer " + Thread.currentThread().getName());

        try {
            while (isRunning) {
//                Thread.sleep(random.nextInt(SLEEPTIME));
                data = new PCData(count.incrementAndGet());
                if(!queue.offer(data, 100, TimeUnit.MILLISECONDS))
                {
                    System.out.println("Failed to put data:" + data);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.interrupted();
        }
    }

    public void stop()
    {
        isRunning = false;
    }
}
